import { CurrentUser } from '@/decorators';
import {
  AddressCreateDto,
  AddressFindDto,
  AddressQueryDto,
  AddressUpdateDto,
} from '@/dtos';
import { AddressService } from '@/services/address.service';
import { ok } from '@/utils';
import { Body, Controller, Delete, Param, Patch, Post } from '@nestjs/common';
import { BaseController } from './base.controller';

@Controller('address')
export class AddressController extends BaseController {
  constructor(private readonly addressService: AddressService) {
    super();
  }

  @Post('find')
  async find(@Body() dto: AddressFindDto, @CurrentUser('id') ownerId: number) {
    return ok(
      await this.prisma.address.findFirst({
        where: {
          ...dto.where,
          isDeleted: false,
          ownerId,
        },
        select: {
          id: true,
          mobile: true,
          name: true,
          isDefault: true,
          address: true,
          area: true,
        },
      }),
    );
  }

  @Post('list')
  async list(@Body() dto: AddressQueryDto, @CurrentUser('id') ownerId: number) {
    return ok(await this.addressService.query(ownerId, dto));
  }

  @Post('create')
  async create(
    @Body() dto: AddressCreateDto,
    @CurrentUser('id') ownerId: number,
  ) {
    return ok(
      await this.addressService.create(ownerId, {
        ...dto.data,
      }),
    );
  }

  @Patch('update')
  async update(
    @Body() dto: AddressUpdateDto,
    @CurrentUser('id') ownerId: number,
  ) {
    return ok(
      await this.addressService.update({
        where: {
          ...dto.where,
          ownerId,
        },
        data: dto.data,
      }),
    );
  }

  @Delete('remove/:id')
  async remove(@Param('id') id: number, @CurrentUser('id') ownerId: number) {
    return ok(
      await this.addressService.remove({
        id,
        ownerId,
      }),
    );
  }
}
